import {
  Component,
  OnInit,
  Inject,
  HostBinding,
  OnDestroy,
  ViewChild,
  ChangeDetectorRef
} from "@angular/core";
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from "@angular/forms";

import { PLATFORM_ID, APP_ID } from "@angular/core";
import { isPlatformServer } from "@angular/common";

import { IEnrollRequest } from "@/user/store/models/user";

import { Store, select } from "@ngrx/store";
import * as fromUser from "@/user/store/reducers/user.reducer";
import { UserActions } from "@/user/store/actions";
import { LocaleService, TranslationService, Language } from "angular-l10n";
import { EhAnimateService } from "@/share/services/eh-animate.service";
@Component({
  selector: "app-enroll",
  templateUrl: "./enroll.component.html",
  styleUrls: ["./enroll.component.scss"],
  animations: [EhAnimateService.fadeInOut()]
})
export class EnrollComponent implements OnInit, OnDestroy {
  @Language() lang: string;

  validateForm: FormGroup;

  loading = false;

  @ViewChild("sliderCodeRef")
  sliderCodeRef;

  req: IEnrollRequest = {
    username: "",
    password: "",
    code: "",
    verify: {}
  };

  isServer: boolean;

  constructor(
    @Inject("NoUsernameValidatorService") private noUsernameValidatorService,
    private fb: FormBuilder,
    @Inject("StoreService") private storeService,
    private store: Store<fromUser.State>,
    @Inject(PLATFORM_ID) private platformId: Object,
    private changeDetectorRef: ChangeDetectorRef
  ) {
    this.isServer = isPlatformServer(this.platformId);
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      username: new FormControl(null, {
        validators: [Validators.required],
        asyncValidators: [
          this.noUsernameValidatorService.validate.bind(
            this.noUsernameValidatorService
          )
        ],
        updateOn: "blur"
      }),
      verify: new FormControl(null, {
        validators: [Validators.required],
        updateOn: "change"
      }),
      password: [null, [Validators.required]],
      password2: [null, [Validators.required, this.confirmationValidator]],
      code: [null, [Validators.required]],
      agree: [false, this.agreeValidator]
    });

    this.addListen();
  }

  ngOnDestroy() {}

  addListen() {
    this.validateForm.valueChanges.subscribe(e => {
      this.req.username = e.username;
      this.req.password = e.password;
      this.req.code = e.code;
      this.req.verify = e.verify;
    });
  }

  async submitForm() {
    const enroll = new UserActions.Enroll({ req: this.req, cpt: this });
    this.store.dispatch(enroll);
  }

  updateConfirmValidator(): void {
    /** wait for refresh value */
    Promise.resolve().then(() =>
      this.validateForm.controls.password2.updateValueAndValidity()
    );
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
  };

  agreeValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { require: true };
    }
  };

  onChangeValidate(e) {
    this.validateForm.controls.verify.setValue(e);
    this.changeDetectorRef.detectChanges();
  }
}
